import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../views/login'
import layout from '../views/layout'
import { getToken } from '../utils/index'
import chart from '../views/layout/chart'
import user from '../views/layout/user'
import enterprise from '../views/layout/enterprise'
import question from '../views/layout/question'
import subject from '../views/layout/subject'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path: '/layout',
    name: 'layout',
    component: layout,
    children: [
      // 子路由中的path 前面不要加 /
      // 参考： https://router.vuejs.org/zh/guide/essentials/nested-routes.html 下面的黑体字
      { path: 'chart', component: chart },
      { path: 'user', component: user },
      { path: 'enterprise', component: enterprise },
      { path: 'question', component: question },
      { path: 'subject', component: subject }
    ]
  }

  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
]

const router = new VueRouter({
  routes
})

// beforeEach 导航守卫
// to 去往何处去
// from 从何处来
// next 控制去不去或者去到哪里，并且必须要调用，否则就会一直卡在这里
// next() 如果里面不加任何参数，就是正常的跳转到下一个页面
// next() 如果里面加了参数，就是跳转到指定页面

// 访问的白名单，可以直接通行
const whiteList = ['/login']
router.beforeEach((to, from, next) => {
  // 访问的路径在白名单中
  if (whiteList.includes(to.path)) {
    next()
  } else {
    if (getToken()) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
